<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .zzc {
            position: fixed;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            background: rgba(0, 0, 0, 0.3);
            z-index: 10;
            display: none;
        }
        
        .mtk {
            width: 450px;
            height: 350px;
            background: #fff;
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
            margin: auto;
            z-index: 11;
            display: none;
            padding: 50px;
            box-sizing: border-box;
        }
    </style>
</head>

<body>
    <button onclick="show()">登录</button>
    <div class="zzc"></div>
    <div class="mtk">
        手机号：<input type="text" id="tel"><br><br> 验证码：
        <input type="text" id="yzm"><span></span><br><br>
        <button onclick="denglu()">登录</button>
        <button onclick="hide()">关闭</button>
    </div>
</body>
<script>
    var span = document.querySelector('span')
        //  模态框显示和隐藏
    var mtk = document.querySelector('.mtk')
    var zzc = document.querySelector('.zzc')

    function show() {
        mtk.style.display = 'block'
        zzc.style.display = 'block'
        span.innerHTML = fn(1000, 9999) //每一次打开模态框验证码重新生成

    }

    function hide() {
        mtk.style.display = 'none'
        zzc.style.display = 'none'
    }


    function fn(min, max) {
        return parseInt(Math.random() * (max - min) + min)
    }

    // 每一次点击验证码更换新的内容
    span.onclick = function() {
        this.innerHTML = fn(1000, 9999)
    }

    // 登录
    function denglu() {
        var telcon = document.querySelector('#tel').value.trim()
        var yzmcon = document.querySelector("#yzm").value.trim()
        if (telcon.length == 0 || yzmcon.length == 0) {
            alert('内容不能为空')
            return false
        }
        if (yzmcon == span.innerHTML) {
            alert('登录成功')
            location.href = './index.html'
        } else {
            alert('验证码错误')
        }
    }
</script>

</html>